<template>
  <view class="publish-container">
    <!-- 标题输入 -->
    <input 
      class="title-input"
      v-model="form.title"
      placeholder="请输入标题（必填）"
      placeholder-class="placeholder-style"
    />

    <!-- 图片上传 -->
    <view class="image-grid">
      <view 
        v-for="(img, index) in tempImages"
        :key="index"
        class="image-item"
      >
        <image :src="img" mode="aspectFill" class="preview-image"></image>
        <view class="delete-btn" @click="removeImage(index)">×</view>
      </view>
      <view 
        v-if="tempImages.length < 9" 
        class="upload-btn"
        @click="handleChooseImage"
      >
        <text class="upload-text">+ 添加图片</text>
        <text class="upload-tip">(最多9张)</text>
      </view>
    </view>

    <!-- 内容输入 -->
    <textarea
      class="content-input"
      v-model="form.content"
      placeholder="请输入内容（必填）"
      placeholder-class="placeholder-style"
      maxlength="500"
    ></textarea>
    <text class="word-count">{{ form.content.length }}/500</text>

    <!-- 提交按钮 -->
    <button class="submit-btn" @click="handleSubmit">发布话题</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      form: {
        title: '',
        content: ''
      },
      tempImages: [],
      uploading: false
    };
  },
  methods: {
    // 选择图片
    async handleChooseImage() {
      if (this.uploading) return;
      
      try {
        const res = await uni.chooseImage({
          count: 9 - this.tempImages.length,
          sizeType: ['compressed'],
          sourceType: ['album']
        });
        this.tempImages = [...this.tempImages, ...res.tempFilePaths];
      } catch (e) {
        uni.showToast({ title: '选择图片失败', icon: 'none' });
      }
    },

    // 删除图片
    removeImage(index) {
      this.tempImages.splice(index, 1);
    },

    // 提交表单
    async handleSubmit() {
      if (!this.form.title.trim()) {
        return uni.showToast({ title: '请输入标题', icon: 'none' });
      }
      if (!this.form.content.trim()) {
        return uni.showToast({ title: '请输入内容', icon: 'none' });
      }
      if (this.form.content.length > 500) {
        return uni.showToast({ title: '内容不能超过500字', icon: 'none' });
      }

      this.uploading = true;
      uni.showLoading({ title: '发布中...' });

      try {
        const userInfo = uni.getStorageSync('userInfo');
        let cloudImages = [];

        // 上传图片
        if (this.tempImages.length > 0) {
          const uploadPromises = this.tempImages.map((img, index) => {
            const fileExt = img.match(/\.\w+$/)[0];
            return uniCloud.uploadFile({
              filePath: img,
              cloudPath: `forum/${Date.now()}_${index}${fileExt}`,
              onUploadProgress: (e) => {
                uni.showLoading({
                  title: `上传中 (${index + 1}/${this.tempImages.length})`
                });
              }
            });
          });

          const results = await Promise.all(uploadPromises);
          cloudImages = results.map(res => res.fileID);
        } 
        // 调用云函数
        await uniCloud.callFunction({
          name: 'add-topic',
          data: {
            title: this.form.title,
            content: this.form.content,
            images: cloudImages,
            author: userInfo.username || '匿名用户',
            mobile: userInfo.mobile,
            type:"review",
          }
        });

        uni.showToast({
                  title: '发布成功，发布话题已提交审核，审核将在1-3个工作日反馈结果',
                  icon: 'none',
                  duration: 4000 // 设置为4秒
                });
        
                // 4秒后执行返回
                setTimeout(() => {
                  // 重置表单
                  this.form = { title: '', content: '' };
                  this.tempImages = [];
                  uni.navigateBack();
                }, 4000);
        
      } catch (e) {
        uni.showToast({ title: '发布失败: ' + e.message, icon: 'none' });
      } finally {
        this.uploading = false;
        uni.hideLoading();
      }
    }
  }
}
</script>

<style scoped>
.publish-container {
  padding: 40rpx;
  background: #f5f1e8;
  min-height: 100vh;
}

.title-input {
  height: 100rpx;
  background: #fff5e6;
  border: 4rpx solid #8b4513;
  border-radius: 12rpx;
  padding: 0 20rpx;
  margin-bottom: 30rpx;
  font-family: '华文楷体';
  font-size: 32rpx;
}

.image-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.image-item {
  position: relative;
  aspect-ratio: 1;
  border: 4rpx solid #8b4513;
  border-radius: 12rpx;
  overflow: hidden;
}

.preview-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  right: 8rpx;
  top: 8rpx;
  width: 40rpx;
  height: 40rpx;
  background: rgba(0,0,0,0.5);
  color: white;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

.upload-btn {
  aspect-ratio: 1;
  border: 4rpx dashed #8b4513;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #fff5e6;
}

.upload-text {
  color: #8b4513;
  font-family: '华文楷体';
  font-size: 28rpx;
}

.upload-tip {
  color: #a0522d;
  font-size: 24rpx;
  margin-top: 10rpx;
}

.content-input {
  height: 400rpx;
  background: #fff5e6;
  border: 4rpx solid #8b4513;
  border-radius: 12rpx;
  padding: 20rpx;
  font-family: '华文楷体';
  font-size: 30rpx;
}

.word-count {
  display: block;
  text-align: right;
  color: #a0522d;
  font-size: 24rpx;
  margin: 10rpx 0 30rpx;
}

.submit-btn {
  background: #b22222;
  color: white;
  height: 90rpx;
  line-height: 90rpx;
  border-radius: 50rpx;
  font-family: '华文行楷';
  font-size: 40rpx;
  box-shadow: 0 4rpx 12rpx rgba(139,69,19,0.3);
}

.placeholder-style {
  color: #a0522d !important;
  font-family: '华文楷体' !important;
}
</style>